﻿/*
	Copyright 2010 Intuitive Solutions

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	   http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

using System;
using Metamorph.Core.Bpm.Events;
using System.Collections.Generic;
using Metamorph.Core.Bpm.Connectors;

namespace Metamorph.Core.Bpm.Activities
{
	public class SubprocessReference : IActivity, ISubprocess
	{
		protected List<IEvent>	lEvents;
		protected ISubprocess	sSubprocess;
		protected Transition	tTransition;

		public SubprocessReference(ISubprocess sSubprocess)
		{
			this.sSubprocess = sSubprocess;
		}

		#region IShape Members

		public string Name
		{
			get
			{
				return sSubprocess.Name;
			}
		}

		public virtual void Init(IBusinessProcess bpBusinessProcess)
		{
			bpBusinessProcess.ExecutionStack.Push(new ExecutionContext(this, bpBusinessProcess));

			bpBusinessProcess.ExecutionStack.Peek().Subprocess = this;

			MetamorphManager.Instance.EventManager.Subscribe(lEvents, bpBusinessProcess);
		}

		public virtual void Next(IBusinessProcess bpBusinessProcess)
		{
			bpBusinessProcess.ExecutionStack.Pop();

			bpBusinessProcess.ExecutionStack.Peek().CurrentShape = tTransition.Target;
		}

		public virtual void Uninit(IBusinessProcess bpBusinessProcess)
		{
			MetamorphManager.Instance.EventManager.Unsubscribe(lEvents, bpBusinessProcess);
		}

		#endregion

		public List<IEvent> Events
		{
			get
			{
				return lEvents;
			}
			set
			{
				lEvents = value;
			}
		}

		#region ISubprocess Members

		public Transition Transition
		{
			get
			{
				return tTransition;
			}
			set
			{
				tTransition = value;
			}
		}

		public IShape InitialShape
		{
			get
			{
				return sSubprocess;
			}
			set
			{
				sSubprocess = (Subprocess)value;
			}
		}

		public ISubprocess Subprocess
		{
			get
			{
				return sSubprocess;
			}
			set
			{
				sSubprocess = value;
			}
		}

		#endregion
	}
}
